package cn.itsource.ymcc.mq;

import cn.itsource.constants.RocketMQConstants;
import cn.itsource.ymcc.domain.MessageStation;
import cn.itsource.ymcc.dto.StationMSG2MQDto;
import cn.itsource.ymcc.service.IMessageStationService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author Eric Chen
 * @since 2022/7/17
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "service-common-consumer-station-message",
        topic = RocketMQConstants.TOPIC_MSG_STATION,
        selectorExpression = RocketMQConstants.TAGS_MSG_STATION)
//站内信的消费者
@Slf4j
public class StationMessageConsumer implements RocketMQListener<MessageExt> {


    @Autowired
    private IMessageStationService stationService ;

    @Override
    public void onMessage(MessageExt message) {

        if(message.getBody() == null || message.getBody().length == 0)return;
        //拿到消息内容
        String jsonContent = new String(message.getBody(), StandardCharsets.UTF_8);
        StationMSG2MQDto dto = JSON.parseObject(jsonContent, StationMSG2MQDto.class);
        //保存站内信

        Date now = new Date();
        MessageStation station = new MessageStation(
                null,dto.getTitle(),dto.getContent(),dto.getType(),now,0,null);

        dto.getUserIds().forEach(userId->{
            station.setUserId(userId);
            stationService.insert(station);
            log.info("保存站内信 {}" , station);
        });
    }
}
